import pandas as pd
import fetchData
import ast

taskStatusMap = {
    "60418b08c679e20044c09c0c": "其他功能解决",
    "64af9ca33bb6c5ae1239f98e": "待开发评估",
    "654da2f56c338454318df4de": "待发布SIT(组内环境已测)",
    "5e0dabc57d161c00217800b8": "开发中",
    "6604cf0816117c37565adb54": "待开发",
    "5e0db98a8fc7b60022d301c6": "待组内评审",
    "6535cfab96d44880e05a51b1": "待测试",
    "6535cfab96d44880e05a51b4": "测试中",
    "5f40cf2267d6500044ec1a29": "待分析",
    "6535cfab96d44880e05a51b7": "已发布SIT(合入release部署)",
    "5e0dabc57d161c00217800b9": "已发布生产",
    "614407e924ae43003fd05019": "已完成（不发版）",
    "603ddbf166272e0044b3d934": "已发布UAT",
    "5e0dabc57d161c00217800b7": "待产品内审",
    "5e0db97739a39700233b0199": "待审阅",
    "6340edfabb167700408b7339": "经评估无法实现",
    "65e80e978ec65144610baca1": "待架构组评审",
}
sprintMap = {
    "202410-2": "202410",
    "202411-1": "202411",
    "202411-2": "202412",
    "202412-1": "202412",
    "202412-2": "202501",
    "202501-1": "202501",
    "202501-2": "202502",
    "202502-1": "202502",
    "202502-2": "202503",
    "202503-1": "202503",
    "202503-2": "202504",
    "202504-1": "202504",
    "202504-2": "202505",
    "202505-1": "202505",
    "202505-2": "202506",
    "202506-1": "202506",
    "202506-2": "202507",
    "202507-1": "202507",
    "202507-2": "202508",
    "202508-1": "202508",
    "202508-2": "202509",
    "202509-1": "202509",
    "202509-2": "202510",
    "202510-1": "202510",
    "202510-2": "202511",
    "202511-1": "202511",
    "202511-2": "202512",
    "202512-1": "202512",
    "202512-2": "202601",
    "202601-1": "202601",
    "202601-2": "202602",
}


def convertCustomFields(customfieldsStr):
    custom_fields = []
    try:
        real_list = ast.literal_eval(customfieldsStr)
        if isinstance(real_list, list):
            custom_fields = real_list
        else:
            print(f"Warning: String '{customfieldsStr}' did not evaluate to a list.")
    except (SyntaxError, ValueError):
        print(f"Error: Could not parse string '{customfieldsStr}' as a Python literal.")
    return custom_fields


def formatData(data):
    tasks = []
    fatherTasksId = []
    for d in data:
        if "parentTaskId" in d and d["parentTaskId"] not in fatherTasksId:
            fatherTasksId.append(d["parentTaskId"])
    for d in data:
        if taskStatusMap.get(d["tfsId"], "unknow") not in [
            "已发布生产",
            "已完成（不发版）",
        ]:
            continue
        if "executorName" in d:
            customFields = d["customfields"]  # convertCustomFields(d["customfields"])
            task = {
                "id": d["id"],
                "taskNo": "DB-" + str(d["uniqueId"]),
                "executorName": d["executorName"],
                "sprintName": d["sprintName"],
                "publishSprint": sprintMap.get(d["sprintName"], "unknow"),
                "status": taskStatusMap.get(d["tfsId"], "unknow"),
                "parentId": d.get("parentTaskId", None),
                "isFather": d["id"] in fatherTasksId,
            }
            task["frontend"] = "未分配"
            task["backend"] = "未分配"
            task["test"] = "未分配"
            task["producter"] = "未分配"
            task["frontend_real_day"] = 0
            task["backend_real_day"] = 0
            task["test_real_day"] = 0
            task["producter_day"] = 0
            task["backend_predict_day"] = 0
            task["frontend_predict_day"] = 0
            task["test_predict_day"] = 0
            for cf in customFields:
                if cf.get("value", None) is None:
                    continue
                if len(cf["value"]) == 0:
                    continue
                if cf["cfId"] == "660be84c797f388d73107b34":
                    task["frontend"] = cf["value"][0]["title"]
                elif cf["cfId"] == "660be86cfdae364d32426542":
                    task["backend"] = cf["value"][0]["title"]
                elif cf["cfId"] == "660be8a675863a6977f65356":
                    task["test"] = cf["value"][0]["title"]
                elif cf["cfId"] == "5f4726706d865fd0fa3754de":
                    task["producter"] = cf["value"][0]["title"]
                elif cf["cfId"] == "61d665f96d08e0319d1feb29":
                    task["designer"] = cf["value"][0]["title"]
                elif cf["cfId"] == "62de3ebad7ab965fbdf6c144":
                    task["frontend_real_day"] = float(cf["value"][0]["title"])
                elif cf["cfId"] == "62de3ed2d51a977b23f42b6b":
                    task["backend_real_day"] = float(cf["value"][0]["title"])
                elif cf["cfId"] == "62de3ee92d8f775082f164f8":
                    task["test_real_day"] = float(cf["value"][0]["title"])
                elif cf["cfId"] == "600e3802727d8e77e7e72ee3":
                    task["backend_predict_day"] = float(cf["value"][0]["title"])
                elif cf["cfId"] == "600e37e3e633856d93e1f21a":
                    task["frontend_predict_day"] = float(cf["value"][0]["title"])
                elif cf["cfId"] == "600e3810f38ec6065a90093d":
                    task["test_predict_day"] = float(cf["value"][0]["title"])
            task["frontend_day"] = (
                (
                    task["frontend_predict_day"]
                    if task["frontend_predict_day"] > 0
                    else task["frontend_real_day"]
                )
                + task["frontend_real_day"]
            ) / 2
            task["backend_day"] = (
                (
                    task["backend_predict_day"]
                    if task["backend_predict_day"] > 0
                    else task["backend_real_day"]
                )
                + task["backend_real_day"]
            ) / 2
            task["test_day"] = (
                (
                    task["test_predict_day"]
                    if task["test_predict_day"] > 0
                    else task["test_real_day"]
                )
                + task["test_real_day"]
            ) / 2
            if task["producter"] != "未分配":
                task["producter_day"] = (
                    task["frontend_day"] + task["backend_day"] + task["test_day"]
                )
            tasks.append(task)
    return tasks


def generateSourceData():
    sprintList = [
        "202410-2",
        "202411-1",
        "202411-2",
        "202412-1",
        "202412-2",
        "202501-1",
        "202501-2",
        "202502-1",
        "202502-2",
        "202503-1",
        "202503-2",
        "202504-1",
        "202504-2",
        "202505-1",
        "202505-2",
        "202506-1",
        "202506-2",
        "202507-1",
        "202507-2",
        "202508-1",
        "202508-2",
        "202509-1",
        "202509-2",
        "202510-1",
    ]

    df = fetchData.fetchData(sprintList)
    tasks_df = pd.DataFrame(formatData(df.to_dict("records")))
    tasks_df.to_csv("./output/detailData.csv", index=False)
